package com.example.data.jpa.dao;

import com.example.data.jpa.entity.User;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.QueryByExampleExecutor;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * <pre>
 * 第 1 种自定义 findByJpql
 * 第 2 种自定义 findCustomerBySpec
 * 第 3 种自定义 @see UserExtOperation # findExtends
 * </pre>
 *
 * @author fanhang
 */
@Repository
public interface UserRepository extends CrudRepository<User, Long>, JpaSpecificationExecutor<User>, QueryByExampleExecutor<User>, UserCustomerOperation {

    /**
     * 第 1 种自定义
     */
    @Query("from User where age > ?1 and remark like '%?2%' ")
    List<User> findByJpql(int age, String remark);

    /**
     * 第 2 种自定义
     */
    default List<User> findCustomerBySpec(int age, String remark) {
        Specification<User> spec = (root, query, cb) -> cb.and(cb.equal(root.get("age"), age), cb.like(root.get("remark"), remark));
        return findAll(spec);
    }

    default List<User> findByExample(int age, String remark) {
        User user = new User();
        user.setAge(age);
        user.setRemark(remark);
        return findBy(Example.of(user), q -> q.sortBy(Sort.by("age")).limit(10).all());
    }
}
